package src.main.java.edu.fpa.day0725;

import java.io.*;

public class TestObjectStream {

    public static File container;

    static {
        container = new File("io"+File.separator+"serd"+File.separator+"people.txt");
        if(!container.exists()){
            try {
                container.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

//        serializePeopleToFile();
//        dederializePeopleFromFile();
        serializePeopleToMemoryAndDesrializeFromMemory();

    }

    /*将对象序列化到文件中*/
    public static void serializePeopleToFile() throws IOException {
        OutputStream out = new FileOutputStream(container);
        ObjectOutputStream outputStream = new ObjectOutputStream(out);
        outputStream.writeObject(new People(20,"csc"));

        outputStream.close();

    }

    /*将对象从文件中反序列化出来*/
    public static void dederializePeopleFromFile() throws IOException, ClassNotFoundException {
        InputStream input= new FileInputStream(container);
        ObjectInputStream objectInputStream = new ObjectInputStream(input);

        People people = (People) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println(people.toString());
    }

    /*将对象序列化到内存中，并读出来*/
    public static void serializePeopleToMemoryAndDesrializeFromMemory() throws IOException, ClassNotFoundException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(out);
        outputStream.writeObject(new People(19,"THL"));


        InputStream input = new ByteArrayInputStream(out.toByteArray());
        ObjectInputStream inputStream = new ObjectInputStream(input);
        People people = (People) inputStream.readObject();
        System.out.println(people.toString());

        inputStream.close();
        outputStream.close();

    }



}

class People implements Serializable{
    private int age;

    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public People(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

